import React, { useEffect, useRef, useState } from "react";
import juicebox from "../plugins/juicebox.js/dist/juicebox.esm.js"; // 假设从 juicebox.js 中引入这个组件

interface HicViewerProps {
    hicFileURL: string;
    locus?: string;
}

const HicViewer: React.FC<HicViewerProps> = ({ hicFileURL, locus }) => {
    const hicContainer = useRef(null);
    const browserInstance = useRef<any>(null); // 存储浏览器实例
    const staticURL = process.env.NEXT_PUBLIC_STATIC_URL + hicFileURL;
    const [hicLoaded, setHicLoaded] = useState(false); // 追踪 IGV 加载状态
    
    const config = {
        backgroundColor: "245,247,249",
        url: staticURL,
        colorScale: "66.20668236071833,255,0,0",
        locus: locus
    };
    useEffect(() => {
        if (hicContainer.current && !browserInstance.current) {
            browserInstance.current = juicebox
                .init(hicContainer.current, config)
                .then((hicBrowser) => {
                    console.log("Juicebox loaded");
                    browserInstance.current = hicBrowser;
                    setHicLoaded(true);
                });
        }

        return () => {
            if (browserInstance.current && browserInstance.current.destroy) {
                try {
                    browserInstance.current.destroy(); // 销毁实例
                } catch (error) {
                    console.error("Error destroying IGV browser:", error);
                }
                browserInstance.current = null; // 清理引用
            }
        };
    }, [hicFileURL]);

    useEffect(() => {
        if (browserInstance.current && locus) {
            browserInstance.current = null
            browserInstance.current = juicebox.init(hicContainer.current, config).then((hicBrowser) => {
                console.log("Juicebox loaded");
                browserInstance.current = hicBrowser;
                setHicLoaded(true);
            }); // 创建并存储浏览器实例
        }
      
    }, [locus])

    return (
        <div>
            {/* Juicebox 会把视图渲染到这个 DOM 元素中 */}
            <div ref={hicContainer} className="h-[110vh] w-full flex items-center justify-center">
                {!hicLoaded && <p className="text-gray-500 text-center mt-20">Loading HiC Viewer...</p>}
            </div>
        </div>
    );
};

export default HicViewer;
